package com.huawei.aiosproj.utils;

import android.content.res.AssetManager;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class AssetsUtils {
    private static void releaseResource(Closeable resource) {
        if (resource != null) {
            try {
                resource.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static boolean isResourcesExist(String modelName, String appDir) {
        File dir = new File(appDir);
        File[] files = dir.listFiles();
        if (files == null) {
            return false;
        }
        for (File file : files) {
            if (file.getName().equals(modelName)) {
                return true;
            }
        }
        return false;
    }

    public static boolean copyResourcesToAppDir(AssetManager am, String modelName, String destDir) {
        InputStream fileInput = null;
        FileOutputStream fileOutput = null;
        ByteArrayOutputStream byteOut = null;
        try {
            fileInput = am.open(modelName);
            String filename = destDir + modelName;

            fileOutput = new FileOutputStream(filename);
            byteOut = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fileInput.read(buffer)) != -1) {
                byteOut.write(buffer, 0, len);
            }
            fileOutput.write(byteOut.toByteArray());
            return true;
        } catch (IOException exception) {
            return false;
        } finally {
            releaseResource(byteOut);
            releaseResource(fileOutput);
            releaseResource(fileInput);
        }
    }
}
